package com.flying.flyingchessgame.security.service;

import com.flying.flyingchessgame.entity.User;
import com.flying.flyingchessgame.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户详情服务实现类
 * <p>
 * 实现Spring Security的UserDetailsService接口，
 * 提供根据用户名加载用户详情的功能，用于用户认证。
 * </p>
 * 
 * @author flying-chess
 * @version 1.0
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    
    private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
    
    @Autowired
    private UserMapper userMapper;

    /**
     * 根据用户名加载用户详情
     * <p>
     * 从数据库中查询用户信息，并转换为Spring Security所需的UserDetails对象。
     * 如果用户不存在，则抛出UsernameNotFoundException异常。
     * </p>
     *
     * @param username 用户名
     * @return UserDetails对象
     * @throws UsernameNotFoundException 当用户不存在时抛出
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.debug("根据用户名加载用户: {}", username);
        
        User user = userMapper.findByUsername(username);
        if (user == null) {
            logger.error("未找到用户名: {}", username);
            throw new UsernameNotFoundException("未找到用户名: " + username);
        }
        
        logger.debug("用户已找到: {}", username);
        return UserDetailsImpl.build(user);
    }
} 